<?php

namespace App\Http\Controllers\H5;

use App\Library\Mall\CartTrait;
use App\Models\Item;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CartController extends BaseController
{
    use CartTrait;

    public function index()
    {

        $recommends = Item::onSale()->orderByDesc('sold')->limit(10)->get();

        return $this->view('h5.cart.index', compact('recommends'));
    }

    public function getJson(Request $request)
    {
        $shops = $this->user()->cartItems()->with(['items'=>function($query){
            return $query->where('uid', $this->uid);
        }])->groupBy('shop_id')->get(['id', 'shop_id', 'shop_name']);

        $items = $this->user->cartItems()->get()->map(function ($item){
            $item->thumb = image_url($item->thumb);
            $item->image = image_url($item->image);
            $item->checked = false;
            return $item;
        });

        return ajaxReturn(['items'=>$items]);
    }

    public function delete(Request $request)
    {
        $itemid = $request->input('itemid');
        $this->user()->cartItems()->where('itemid', $itemid)->delete();
        return ajaxReturn();
    }
}
